import React, { useState, useEffect } from "react";
import { Form, Input, Button, Table, message } from "antd";

const TableForm = () => {
  const [form] = Form.useForm();
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(5);
  const [dataSource, setDataSource] = useState([]);

  useEffect(() => {
    // 初始化数据
    const initialData = Array.from({ length: 7 }, (_, index) => ({
      key: index.toString(),
      name: "",
      age: "",
    }));
    setDataSource(initialData);
  }, []);

  const columns = [
    {
      title: "Name",
      dataIndex: "name",
      render: (text, record) => (
        <Form.Item name={["table", record.key, "name"]} rules={[{ required: true, message: "Please input name" }]}>
          <Input />
        </Form.Item>
      ),
    },
    {
      title: "Age",
      dataIndex: "age",
      render: (text, record) => (
        <Form.Item name={["table", record.key, "age"]} rules={[{ required: true, message: "Please input age" }]}>
          <Input />
        </Form.Item>
      ),
    },
  ];

  const handleSubmit = async () => {
    try {
      // 首先进行表单校验
      await form.validateFields();

      // 获取所有表单项的值
      const allValues = form.getFieldsValue(["table", "extraField1", "extraField2"]);
      console.log("All form values:", allValues);

      // 手动校验所有页面的必填项
      let isValid = true;
      Object.keys(allValues.table).forEach((key) => {
        const item = allValues.table[key];
        if (!item || !item.name || !item.age) {
          message.error(`Row ${parseInt(key) + 1} has missing required fields.`);
          isValid = false;
        }
      });

      if (isValid) {
        message.success("All fields are valid!");
        // 在这里可以进行提交操作
      }
    } catch (errorInfo) {
      console.log("Validation Failed:", errorInfo);
    }
  };

  const handleTableChange = (pagination) => {
    setCurrentPage(pagination.current);
  };

  return (
    <Form form={form} initialValues={{ table: dataSource }}>
      <Form.Item label="姓名" name="extraField1">
        <Input />
      </Form.Item>
      <Form.Item label="手机号" name="extraField2">
        <Input />
      </Form.Item>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          current: currentPage,
          pageSize,
          total: dataSource.length,
          onChange: (page) => setCurrentPage(page),
        }}
        rowKey="key"
      />
      <Button type="primary" onClick={handleSubmit}>
        Submit
      </Button>
    </Form>
  );
};

export default TableForm;
